<?php

namespace app\modules\pay\utils;

class SignUtil {

    /**
     * MD5签名
     * @param $data
     * @param $key
     * @return string
     */
    public static function sign($data,$key=null){
        //按字典序排序参数
        ksort($data);
        return strtoupper(md5(self::toUrlParams($data) . "&key=".$key));
    }

    /**
     * MD5签名验证
     * @param $data
     * @param $key
     * @return string
     */
    public static function verify($data,$key){
        return self::sign($data,$key);
    }

    /**
     * 格式化参数格式化成url参数
     */
    protected static function toUrlParams($values)
    {
        $buff = "";
        foreach ($values as $k => $v)
        {
            if($k != "sign" && $k != 'pay_channel' && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }
}
